<template>
  <Layout>
    <Spin fix v-if="isSpin">
      <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
      <div>正在生成导出文件，请稍后</div>
    </Spin>
    <Form ref="form1" :model="form1" :label-width="120">
      <Row class="query-form" style="padding-top: 10px">

        <Col span="8">
          <FormItem label="所属单位：" prop="belongOrtrainOrgId">
            <company-select v-model="form1.orgName" class="query-form-el"></company-select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="二级集团：" prop="belongOrtrainOrgId">
            <two-level-org org-code class="query-form-el" v-model="form1.twoLevelOrgId"></two-level-org>
          </FormItem>
        </Col>
        <Col span="8" v-show="switchFlag">
          <FormItem label="演练名称：" prop="trainName">
            <Input class="query-form-el" type="text" v-model="form1.trainName"></Input>
          </FormItem>
        </Col>
        <Col span="8" v-show="!switchFlag">
          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form" style="padding-top: 10px">
        <Col span="8">
          <FormItem label="计划演练时间：" prop="startDate">
            <DatePicker class="query-form-el" v-model="form1.startDate" format="yyyy-MM-dd"
                        type="daterange" placement="bottom-start" placeholder="请选择检查时间段" 
                        @on-change="(date) => onSelectFieldQueryDateRange(date, 'startDate')"></DatePicker>
          </FormItem>
        </Col>
        <Col span="8" offset="8">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>


      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
          <Button type="primary" class="ivu-btn-add" icon="md-cloud-download" @click="download">导出</Button>
          <!--<Button size="large"  class="ivu-btn-delete" icon="md-trash" @click="batDelete">删除</Button>-->
        </Col>
      </Row>
    </Form>

    <Table ref='table' :height="tableHeight" :loading="loading" no-data-text="没有查询到相关数据!" @on-sort-change="querySort"
           @on-selection-change='getSelectRows'
           border :columns="columns1" :data="dataTable" size="small">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
              @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
              show-total show-sizer show-elevator/>
      </Col>
    </Row>
    <Modal :title="add?'应急演练信息新增':'应急演练信息修改'" :transfer=false v-model="model1" :width=700
           :styles="{height:'559px'}" class-name='limit-height-dialog'>
      <Form ref="form1datacopy" :model="form1datacopy" :rules="ruleCustom" label-position="top">
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="计划名称：" prop="measureId">
              <Input type="text" readonly @on-focus="openSupplyModel"
                     v-model="form1datacopy.measureName"></Input>
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="演练名称：" prop="trainName">
              <Input type="text" v-model="form1datacopy.trainName"></Input>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="演练单位：" prop="trainOrgId">
              <cascaderDom class="query-form-el" style="padding-top: 4px;width: 100%;" ref="carOrg"
                           @setOrgInfo="setCurrentOrgId" @setOrgname="setCurrentOrgName"
                           :currentOrgId="form1datacopy.trainOrgId"
                           :currentOrgName="form1datacopy.orgName" :orgTree="true"></cascaderDom>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="演练总指挥：" prop="commander">
              <Input type="text" v-model="form1datacopy.commander"></Input>
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="计划演练时间：" prop="startDate">
              <DatePicker v-model="form1datacopy.startDate" type="date" style="width: 100%;"
                          placeholder="请输入"></DatePicker>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="填报人：" prop="createUserName">
              <Input type="text" v-model="form1datacopy.createUserName" readonly></Input>
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="填报人电话：" prop="cellPhone">
              <Input type="text" v-model="form1datacopy.cellPhone"></Input>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">

          <Col span="23">
            <FormItem label="演练照片：">
              <div style="width: 100%">
                <Upload ref="upload"
                        :before-upload="beforeUpload1"
                        :show-upload-list="true"
                        :format="['jpg','jpeg','png']"
                        accept="image/jpg, image/jpeg,image/png,image/gif,image/bmp"
                        :max-size="10240"
                        multiple
                        type="drag"
                        :action="fileUrl">
                  <div style="padding: 20px">
                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                    <p>点击将文件拖拽到这里上传</p>
                    <span style="font-size:8px;color: #797a64">支持扩展名：.jpg .png .jpeg...</span>
                  </div>
                </Upload>
              </div>

              <div v-show="uploadImgList.length>0" v-for="(item,index) in uploadImgList" :key='item'>
                <a @click="downloadFile1(form1datacopy.trainId,item,index)">{{ item.fileName }}</a>
                <Button type="text" icon="md-trash" @click="removeImg(item.id)"
                        style="margin-left: 5px;margin-bottom: 3px"/>
                <Progress v-show="uploadListVisibleImg[index]" :percent="uploadListVisibleImg[index]"></Progress>
              </div>
            </FormItem>
          </Col>


        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">

          <Col span="23">
            <FormItem label="演练文档：">
              <div style="width: 100%">
                <Upload ref="upload"
                        :before-upload="beforeUpload"
                        :show-upload-list="true"
                        :max-size="10240"
                        multiple
                        type="drag"
                        :action="fileUrl">
                  <div style="padding: 20px">
                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                    <p>点击将文件拖拽到这里上传</p>
                    <span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>
                  </div>
                </Upload>
              </div>

              <div v-show="uploadList.length>0" v-for="(item,index) in uploadList" :key='item'>
                <a @click="downloadFile(form1datacopy.trainId,item,index)">{{ item.fileName }}</a>
                <Button type="text" icon="md-trash" @click="remove1(item.id)"
                        style="margin-left: 5px;margin-bottom: 3px"/>
                <Progress v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
              </div>
            </FormItem>
          </Col>


        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="演练评价：">
              <Input v-model="form1datacopy.evaluate" type="textarea" :rows="2"/>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="改进计划：">
              <Input v-model="form1datacopy.plan" type="textarea" :rows="2"/>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="演练地点：" prop="trainAddress">
              <Input v-model="form1datacopy.trainAddress" type="textarea" :rows="2"/>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="参加人员：" prop="participants">
              <Input v-model="form1datacopy.participants" type="textarea" :rows="2"/>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="演练内容：" prop="trainContent">
              <Input v-model="form1datacopy.trainContent" type="textarea" :rows="2"/>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="备注：" prop="notes">
              <Input v-model="form1datacopy.notes" type="textarea" :rows="2"/>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button type="primary" class='ivu-btn-save' :loading="buttonLoading" @click="submit('form1datacopy')">
          确定
        </Button>
        <Button type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
      </div>
    </Modal>
    <Modal class="modal-view-detail" title="应急演练信息" :transfer=false v-model="model2" :width=800>
      <Row>
        <Col span="24">
          <Form :model="form1datacopy" :label-width="160">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="演练单位：" prop="trainOrgId">
                  {{ form1datacopy.orgName }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="应急计划名称：">
                  {{ form1datacopy.measureName }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="演练名称：">
                  {{ form1datacopy.trainName }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">

              <Col span="11">
                <FormItem label="演练总指挥：">
                  {{ form1datacopy.commander }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="计划演练时间：">
                  {{ formateDate(form1datacopy.startDate) }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="填报人：">
                  {{ form1datacopy.createUserName }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="填报人电话：">
                  {{ form1datacopy.cellPhone }}
                </FormItem>
              </Col>

            </Row>

            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="演练评价：">
                  {{ form1datacopy.evaluate }}
                </FormItem>
              </Col>

            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="改进计划：">
                  {{ form1datacopy.plan }}
                </FormItem>
              </Col>

            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="演练地点：" prop="trainAddress ">
                  {{ form1datacopy.trainAddress }}
                </FormItem>
              </Col>

            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="参加人员：" prop="participants ">
                  {{ form1datacopy.participants }}
                </FormItem>
              </Col>

            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="备注：" prop="notes ">
                  {{ form1datacopy.notes }}
                </FormItem>
              </Col>

            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="计划文档：">
                  <div v-show="uploadList.length>0" v-for="(item,index) in uploadList" :key='item'>
                    <a @click="downloadFile(form1datacopy.trainId,item,index)">{{ item.fileName }}</a>
                    <Progress v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
                  </div>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="演练照片：">
                  <div v-show="uploadImgList.length>0" v-for="(item,index) in uploadImgList" :key='item'>
                    <a @click="downloadFile1(form1datacopy.trainId,item,index)">{{ item.fileName }}</a>
                    <Progress v-show="uploadListVisibleImg[index]" :percent="uploadListPercentImg[index]"></Progress>
                  </div>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="model2=false">关闭</Button>
      </div>
    </Modal>


    <Modal title="应急计划选择" :transfer=false footer-hide v-model="planModel" :width=900>
      <planSelect ref="selMission" @selectMission="selectMission" :type="this.type">
      </planSelect>
    </Modal>
  </Layout>
</template>

<script>
import {Api} from '../../../../api'
import {sessionStorage} from '../../../../common/cacheUtils.js';
import planSelect from "../plan/planSelect.vue"
import {formatDate} from "@/tools";

var cascaderDom = () => import('@/components/cascader-dom.vue');

export default {
  components: {
    cascaderDom,
    planSelect
  },
  data() {
    return {
      isSpin: false,
      planModel: false,
      fileUrl: Api.interestedPartiesUserFile,
      setCurrentName: {},
      uploadList: [],
      uploadImgList: [],
      esTypeList: [],
      uploadListVisible: [],
      uploadListPercent: [],
      uploadListVisibleImg: [],
      uploadListPercentImg: [],
      upUrl: Api.uploadPTWSchemeFile,
      switchFlag: false,
      form1: {},
      type: this.$route.query.id,
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      dataTable: [],
      columns1: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          title: '演练名称',
          width: 150,
          align: 'center',
          key: 'trainName',
        },
        {
          title: '计划名称',
          width: 150,
          align: 'center',
          key: 'measureName',
        },
        {
          title: '演练单位',
          align: 'center',
          minWidth: 150,
          key: 'orgName',
        },
        {
          title: '填报人',
          width: 150,
          align: 'center',
          key: 'createUserName',
        },
        {
          title: '填报人电话',
          width: 150,
          align: 'center',
          key: 'cellPhone',
        },
        {
          title: '计划演练时间',
          width: 150,
          align: 'center',
          key: 'startDate',
          sortable: 'custom',
          render: (h, params) => {
            return h('div', [
              (this.formatDate(new Date(params.row.startDate), 'yyyy-MM-dd'))
            ]);
          }
        },
        {
          title: '演练地点',
          width: 150,
          align: 'center',
          key: 'trainAddress',
        },
        {
          title: '参加人员',
          width: 150,
          align: 'center',
          key: 'participants',
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 200,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px'
                },
                on: {
                  click: () => {
                    this.showData(params, 1);
                  }
                }
              }, '详情'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                },
                on: {
                  click: () => {
                    this.showData(params, 2);
                  }
                }
              }, '修改'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                  color: 'red'
                },
                on: {
                  click: () => {

                    this.$Modal.confirm({
                      title: '数据删除',
                      content: '<p>确定删除该条信息</p>',
                      okText: '确认',
                      onOk: () => {
                        this.deleteData(params);
                      },
                      cancelText: '取消'
                    });

                  }
                }
              }, '删除')
            ]);
          }
        },

      ],
      user: sessionStorage('userId').getObject('userId'),
      ruleCustom: {
        cellPhone: [{
          validator: (rule, value, callback) => {
            if (!(/^1[3456789]\d{9}$/.test(this.form1datacopy.cellPhone))) {
              callback(' ');
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'blur'
        }],
        startDate: [{
          validator: (rule, value, callback) => {
            if (!this.form1datacopy.startDate) {
              callback(' ');
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        trainName: [
          {required: true, message: '  ', trigger: 'blur'}
        ],
        commander: [
          {required: true, message: '  ', trigger: 'change'}
        ],
        trainOrgId: [
          {required: true, message: '  ', trigger: 'change'}
        ],
        leaderId: [
          {required: true, message: '  ', trigger: 'change'}
        ],
        measureId: [
          {required: true, message: '  ', trigger: 'change'}
        ],

      },
      add: false,
      model1: false,
      buttonLoading: false, model2: false,
      showdata: {},
      staffOrgId: '',
      staffOrgName: '',
      form1datacopy: {},
      files: [],
      tableHeight: 10, loading: false,
      currentOrgId: '',
      currentOrgName: '',
      measure: {},
      showMeasure: false,
      codingSortList: [],
    }
  },
  mounted() {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    // this.selectCodingSort();
    this.query();
  },
  methods: {
    onSelectFieldQueryDateRange(data, filed) {
        if (data[0] === "" || data[1] === "") {
            this.form1[filed + 'From'] = null;
            this.form1[filed + 'To'] = null;
        } else {
            this.form1[filed + 'From'] = data[0] + ' 00:00:00';
            this.form1[filed + 'To'] = data[1] + ' 23:59:59';
        }
    },
    getFiles() {
      let url = this.fileUrl + '/' + this.form1datacopy.trainId + '/files/train'
      this.$http.get(url).then((res) => {
        if (res.data.result == "success") {
          this.uploadList = res.data.data
          let index = 0;
          this.uploadList.forEach(item => {
            this.uploadListPercent[index] = 0;
            this.uploadListVisible[index] = false;
            index++;
          })
        }
      })
    },
    getFiles1() {
      let url = this.fileUrl + '/' + this.form1datacopy.trainId + '/files/trainImg'
      this.$http.get(url).then((res) => {
        if (res.data.result == "success") {
          this.uploadImgList = res.data.data
          let index = 0;
          this.uploadImgList.forEach(item => {
            this.uploadListPercentImg[index] = 0;
            this.uploadListVisibleImg[index] = false;
            index++;
          })
        }
      })
    },
    beforeUpload(file) {
      let formData = new FormData();
      formData.append("files", file); // 文件对象
      let url = this.fileUrl + '/' + this.form1datacopy.trainId + '/files/train'
      this.$http.post(url, formData).then((res) => {
        if (res.data.result == "success") {
          this.$Message.info("文件上传成功")
          this.getFiles();
        }
      })
      return false
    },
    beforeUpload1(file) {
      let formData = new FormData();
      formData.append("files", file); // 文件对象
      let url = this.fileUrl + '/' + this.form1datacopy.trainId + '/files/trainImg'
      this.$http.post(url, formData).then((res) => {
        if (res.data.result == "success") {
          this.$Message.info("文件上传成功")
          this.getFiles1();
        }
      })
      return false
    },
    selectMission(row) {

      this.planModel = false;
      this.form1datacopy.measureName = row.planName;
      this.form1datacopy.measureId = row.id;


    },
    downloadFile1(guideId, file, index) {
      let url = this.fileUrl + '/file/' + file.id;
      let _this = this;
      this.uploadListVisibleImg[index] = true;
      this.$http.get(url, {
        responseType: 'blob',      //告诉服务器我们需要的响应格式
        progress: function (e) {
          _this.$set(_this.uploadListPercentImg, index, 100 * (e.loaded / e.total));
        }
      }).then((res) => {

        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = file.fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    downloadFile(guideId, file, index) {
      let url = this.fileUrl + '/file/' + file.id;
      let _this = this;
      this.uploadListVisible[index] = true;
      this.$http.get(url, {
        responseType: 'blob',      //告诉服务器我们需要的响应格式
        progress: function (e) {
          _this.$set(_this.uploadListPercent, index, 100 * (e.loaded / e.total));
        }
      }).then((res) => {

        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = file.fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    removeImg(id) {
      let url = this.fileUrl + '/file/' + id;
      this.$http.delete(url).then((res) => {
        this.getFiles1()
      })
    },

    remove1(id) {
      let url = this.fileUrl + '/file/' + id;
      this.$http.delete(url).then((res) => {
        this.getFiles()
      })
    },

    setUserName1(data) {
      this.form1datacopy.userName = data;
    },
    setUserId1(data) {
      this.form1datacopy.leaderId = data[data.length - 1];
    },
    download() {
      let data = {
        orgId: sessionStorage('userId').getObject('userId').companyId,
        type: this.$route.query.id
      }
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      this.isSpin = true;
      this.$http.get(Api.downloadEmergencyTrain, {
        params: data,
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = "应急演练(" + formatDate(new Date(), "yyyy-MM-dd") + ").xlsx" //标题
        aLink.click()
        document.body.appendChild(aLink)
        this.isSpin = false;
      })
    },
    deleteData(params) {
      let url = Api.deleteEmergencyTrain;
      this.$http.delete(url + '/' + params.row.trainId, {params: {}}).then((res) => {
        if (res.data.status === 200) {
          this.$Message.success('成功');
          this.query()
        } else if (res.data.status === 201) {
          this.$Message.error(res.data.msg);

        }
      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })
    },
    formateDate(date) {
      if (date) {
        return this.formatDate(new Date(date), 'yyyy-MM-dd');
      } else {
        return "";
      }
    },
    setOrgId(data) {
      this.form1.trainOrgId = data[data.length - 1];
    },
    setOrgName(data) {
      this.form1.orgName = data;
    },
    setOrgId1(data) {
      this.form1.trainOrgId = data[data.length - 1];
    },
    setOrgName1(data) {
      this.form1.orgName = data;
    },
    setCurrentOrgId(data) {
      this.form1datacopy.trainOrgId = data[data.length - 1];
    },
    setCurrentOrgName(data) {
      this.form1datacopy.orgName = data;
    },
    getSelectRows(rows) {
      this.deleteRows = rows;
    },
    batDelete() {

    },
    addInfo() {
      this.form1datacopy = {
        trainId: this.get_uuid(),
        createUserName: this.user.userName,
        cellPhone: this.user.mobileNumber,
      };
      this.uploadList = [];
      this.uploadImgList = [];
      this.model1 = true;
      this.add = true;
    },
    get_uuid() {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4";
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
      s[8] = s[13] = s[18] = s[23] = "-";

      let uuid = s.join("");
      let reg = new RegExp("-", "g");
      let a = uuid.replace(reg, "");
      return a;
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    handleCancel() {
      this.form1datacopy = {};
      this.model1 = false;
    },
    selectCodingSort() {
      this.$http.get(Api.queryCodeDetailBySortId + '/WT-000001', {params: {}}).then((res) => {
        this.esTypeList = res.data.data;
      });
      this.$http.get(Api.queryCodeDetailBySortId + '/WL-000001', {params: {}}).then((res) => {
        this.esLevelList = res.data.data;
      });

      this.$http.get(Api.queryCodeDetailBySortId + '/PL-000001', {params: {}}).then((res) => {
        this.emLevelList = res.data.data;
        this.codingSortList = this.codingSortList.concat(this.emLevelList);
      });
      this.$http.get(Api.queryCodeDetailBySortId + '/ET-000001', {params: {}}).then((res) => {
        this.eventTypeList = res.data.data;
        this.codingSortList = this.codingSortList.concat(this.eventTypeList);
      });
      this.$http.get(Api.queryCodeDetailBySortId + '/PL-000010', {params: {}}).then((res) => {
        this.emTypeList = res.data.data;
        this.codingSortList = this.codingSortList.concat(this.emTypeList);
      });
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      setTimeout(() => {
        this.$refs.trainOrg1.setCurrentOrg();
        this.$refs.trainOrg2.setCurrentOrg();
      }, 100)
      if (!this.switchFlag) {
        this.tableHeight = this.tableHeight + 44;
      } else {
        this.tableHeight = this.tableHeight - 44;
      }
    },
    reset() {
      this.form1 = {};
      // this.$refs.queryOrgCascader.resetCurrentOrg();
      this.staffOrgId = '';
      this.staffOrgName = '';
      this.query();

    },
    query() {
      this.loading = true;
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        orgId: sessionStorage('userId').getObject('userId').companyId,
        type: this.$route.query.id
      };
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      let url = Api.queryEmergencyTrain;
      this.$http.get(url, {params: data}).then((res) => {
        this.dataTable = res.data.data.data;
        this.pagedata.total = res.data.data.totalSize;
        this.loading = false;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    showData(data, flag) {
      this.currentOrgId = data.row.trainOrgId;
      this.currentOrgName = data.row.orgName;

      if (flag == 1) {
        //查看页面
        this.form1datacopy = data.row;
        this.getFiles();
		this.getFiles1();
        this.form1datacopy.startDate = this.formatDate(new Date(this.form1datacopy.startDate), 'yyyy-MM-dd');
        this.model2 = true;
      } else {

        //修改页面
        this.add = false;
        // this.form1datacopy.purchaseDate = this.formatDate(new Date(this.showdata.purchaseDate), 'yyyy-MM-dd');
        this.form1datacopy = JSON.parse(JSON.stringify(data.row));
        this.form1datacopy.setCurrentName = {value: data.row.userName, label: data.row.userName};
        this.getFiles()
		this.getFiles1();
        this.model1 = true;
      }
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    async upload() {

    },
    submit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          if (this.form1datacopy.startDate != undefined) {
            this.form1datacopy.startDate = this.formatDate(new Date(this.form1datacopy.startDate), 'yyyy-MM-dd');
          }
          this.form1datacopy.emeType = this.$route.query.id;
          let userId = sessionStorage('userId').getObject('userId').userId;
          let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
          if (this.add) {
            this.form1datacopy.createUserId = userId;
            this.form1datacopy.createOrgId = orgId;
            this.$http.post(Api.saveEmergencyTrain, this.form1datacopy).then((res) => {
              if (res.data.status === 200) {
                this.$Message.success('成功');
                this.model1 = false;
                this.query()

              } else if (res.data.status === 201) {
                this.$Message.error(res.data.msg);
                this.model1 = false;
              }
              this.buttonLoading = false
            }).catch(e => {
              this.model1 = false;
              this.query();
              this.buttonLoading = false
              this.$Message.error("数据获取失败")
            })
          } else {
            this.form1datacopy.updateUserId = userId;
            this.form1datacopy.updateOrgId = orgId;
            this.$http.post(Api.updateEmergencyTrain, this.form1datacopy).then((res) => {
              if (res.data.status === 200) {
                this.$Message.success('成功');
                this.model1 = false;
                this.query()

              } else if (res.data.status === 201) {
                this.$Message.error(res.data.msg);
                this.model1 = false;
              }
              this.buttonLoading = false
            }).catch(e => {
              this.model1 = false;
              this.query();
              this.buttonLoading = false
              this.$Message.error("数据获取失败")
            })
          }


        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
    openSupplyModel() {
      this.planModel = true;
    },
    getSelectData(row) {
      this.form1datacopy.measureId = row.emId;
      this.form1datacopy.measureName = row.emName;
      this.measureForSelect = false;
    },
    getMeasure() {
      this.measure.releaseDate = this.formatDate(new Date(this.measure.releaseDate), 'yyyy-MM-dd');
      this.showMeasure = true;
    },
    getCodingSortName(codingCodeId) {
      let codingName = ''
      try {
        this.codingSortList.forEach(function (e) {
          if (codingCodeId == e.codingCodeId) {
            codingName = e.codingName
            throw Error();
          }
        });
      } catch (e) {
      }
      return codingName;
    },
    querySort({column, key, order}){
      this.form1.key = key;
      this.form1.order = order;
      this.query();
    }

  },
  watch: {
    "model1": function (qw, er) {
      if (qw && this.model1 && !this.add) {
        setTimeout(() => {
          this.$refs.carOrg.setCurrentOrg();
          this.$refs.childUser.setCurrentUser();
        }, 100)
      } else {
        this.$refs.carOrg.resetCurrentOrg();
        this.$refs.childUser.resetCurrentOrg();
      }
    },

  },

}
</script>

<style lang='css' scoped>
@import '../../../../index.css';

.demo-spin-icon-load{
  animation: ani-demo-spin 1s linear infinite;
}
</style>
